package com.Ajava1704.yiburenwubianpai;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @类名: com.Ajava1704.yiburenwubianpai
 * @作者: lgt
 * @创建时间: 2020-02-10 21:04
 * @描述:
 **/
public class TestYiBuRenWuBianPai {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //需求执行完第一个线程，根据第一个线程的结果运行第二个
       /* CompletableFuture.supplyAsync(()->{
            return "hello";
        }).thenAccept(y->{
            System.out.println(y+"999999");     //hello999999
        });*/

        //任务的合并  线程三依赖一和二的结果
        /*CompletableFuture.supplyAsync(()->{
            return "hello";
        }).thenCombineAsync(CompletableFuture.supplyAsync(()->{return "world !";}),(x,y)->{
            return x+y;
        }).thenAccept(L->{
            System.out.println("********"+L);   //********helloworld !   结果
        });*/



        //所有的线程中有一个先执行完的
        CompletableFuture<String> st1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "T=01";
        });

        CompletableFuture<String> st2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "T=02";
        });

        CompletableFuture<String> st3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "T=03";
        });

        /*CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(st1, st2, st3);
        System.out.println(objectCompletableFuture.get()); //睡眠最短的   */

        /*CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(st1, st2, st3);
        System.out.println(voidCompletableFuture.get()); //null  */

        String str = "01";
        CompletableFuture<String> exceptionally = CompletableFuture.supplyAsync(() -> {
            if (str.equals("01")) {
                throw new RuntimeException("-------出错啦----");
            }
            return "T=20";
        }).exceptionally((e) -> {
            e.printStackTrace();
            return "error";
        });
        System.out.println(exceptionally.get());   //T=20
        System.out.println("************");
    }
}
